package com.epam.productxslt.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.productxslt.command.Command;
import com.epam.productxslt.command.CommandManager;
import com.epam.productxslt.exception.ProductException;
import com.epam.productxslt.util.ResourceManager;


public final class ProductController extends HttpServlet{
	private static final long serialVersionUID = -6860234399342814360L;	
	private static final Logger logger =  Logger.getLogger(ProductController.class);
	@Override
	public void init() throws ServletException {
		super.init();
		RequestContent.XML_PATH= getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.XML_PATH));
		RequestContent.CATEGORIES_XSL_PATH = getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.CATEGORIES_XSL_PATH));
		RequestContent.SUBCATEGORIES_XSL_PATH = getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.SUBCATEGORIES_XSL_PATH));
		RequestContent.GOODS_XSL_PATH = getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.GOODS_XSL_PATH));
		RequestContent.ADD_GOODS_XSL_PATH = getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.ADD_GOOD_XSL_PATH));
		RequestContent.SAVE_GOODS_XSL_PATH = getServletContext().getRealPath(ResourceManager.getProperty(ResourceManager.SAVE_GOOD_XSL_PATH));
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}
	
	private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		RequestContent requestContent = new RequestContent(req);
		requestContent.setResponseWriter(resp.getWriter());
		Command command = CommandManager.getCommand(requestContent);
		try	{
			command.execute(requestContent);
			if(requestContent.getRedirectPath() != null){
				resp.sendRedirect(requestContent.getRedirectPath());
			}
		} catch (ProductException e) {
			String errorPagePath = ResourceManager.getProperty(ResourceManager.ERROR_PAGE_PATH);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(errorPagePath);
			dispatcher.forward(req, resp);
			logger.error(e);
		}
	}
}
